package estore.view;

import estore.model.Product;
import estore.service.ProductService;
import estore.service.ProductSorters;
import java.io.*;
import java.util.*;

public class ConsoleShop {
    private final ProductService productService = new ProductService();
    private final Map<String, Integer> shoppingCart = new HashMap<>();
    private final Scanner scanner;

    public ConsoleShop() {
        this.scanner = new Scanner(System.in);
        productService.initTestData();
    }

    public void start() {
        while (true) {
            showMenu();
            int choice;
            try {
                choice = scanner.nextInt();
                scanner.nextLine();
            } catch (InputMismatchException var3) {
                System.out.println("输入错误！请输入数字选项。");
                scanner.nextLine();
                continue;
            }

            switch (choice) {
                case 1:
                    browseProducts(null);
                    break;
                case 2:
                    addToCart();
                    break;
                case 3:
                    viewCart();
                    break;
                case 4:
                    showSortedProducts();
                    break;
                case 5:
                    productService.saveData();
                    System.out.println("感谢使用，再见！");
                    return;
                case 99:
                    backupData();
                    break;
                default:
                    System.out.println("无效的选项，请重新输入！");
            }
        }
    }

    private void backupData() {
        String sourcePath = productService.getDataFilePath();
        String backupPath = sourcePath + ".bak";

        File sourceFile = new File(sourcePath);
        if (!sourceFile.exists()) {
            System.out.println("源数据文件不存在，无法备份！");
            return;
        }

        try (FileInputStream fis = new FileInputStream(sourceFile);
             FileOutputStream fos = new FileOutputStream(backupPath)) {

            byte[] buffer = new byte[1024];
            int readLen;
            while ((readLen = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, readLen);
            }
            fos.flush();
            System.out.println("备份成功！备份文件路径：" + backupPath);

        } catch (IOException e) {
            System.err.println("备份失败：" + e.getMessage());
        }
    }

    private void showMenu() {
        System.out.println("\n----- 欢迎来到商城 -----");
        System.out.println("1. 浏览所有商品（默认排序）");
        System.out.println("2. 添加商品到购物车");
        System.out.println("3. 查看购物车");
        System.out.println("4. 自定义排序浏览商品");
        System.out.println("5. 退出");
        System.out.print("请输入您的选择: ");
    }

    private void browseProducts(Comparator<Product> comparator) {
        System.out.println("\n--- 商品列表 ---");
        List<Product> products = productService.getAllProducts();
        if (products.isEmpty()) {
            System.out.println("商店里还没有商品。");
        } else {
            if (comparator != null) {
                products.sort(comparator);
            } else {
                Collections.sort(products);
            }
            products.forEach(System.out::println);
        }
    }

    private void showSortedProducts() {
        System.out.println("\n--- 排序方式选择 ---");
        System.out.println("1. 按价格从低到高");
        System.out.println("2. 按价格从高到低");
        System.out.println("3. 按库存从多到少");
        System.out.println("4. 返回主菜单");
        System.out.print("请选择排序方式: ");
        int choice;
        try {
            choice = scanner.nextInt();
            scanner.nextLine();
        } catch (InputMismatchException var3) {
            System.out.println("输入错误！请输入数字选项。");
            scanner.nextLine();
            return;
        }

        Comparator<Product> comparator = null;
        switch (choice) {
            case 1 -> comparator = ProductSorters.BY_PRICE_ASC;
            case 2 -> comparator = ProductSorters.BY_PRICE_DESC;
            case 3 -> comparator = ProductSorters.BY_STOCK_DESC;
            case 4 -> {
                return;
            }
            default -> System.out.println("无效的选项，将使用默认排序。");
        }
        browseProducts(comparator);
    }

    private void addToCart() {
        System.out.println("\n--- 添加商品到购物车 ---");
        System.out.print("请输入商品ID：");
        String productId = scanner.nextLine().trim();

        Product product = productService.getProductById(productId);
        if (product == null) {
            System.out.println("错误：未找到ID为" + productId + "的商品！");
            return;
        }

        System.out.print("请输入购买数量：");
        int quantity;
        try {
            quantity = Integer.parseInt(scanner.nextLine().trim());
        } catch (NumberFormatException e) {
            System.out.println("错误：数量必须是整数！");
            return;
        }

        if (quantity <= 0) {
            System.out.println("错误：数量必须大于0！");
            return;
        }

        if (product.getStock() < quantity) {
            System.out.println("错误：库存不足！当前库存：" + product.getStock() + "件");
            return;
        }

        shoppingCart.put(productId, shoppingCart.getOrDefault(productId, 0) + quantity);
        System.out.println("成功添加 " + product.getName() + " x" + quantity + " 到购物车！");
    }

    private void viewCart() {
        System.out.println("\n--- 我的购物车 ---");
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车是空的，快去添加商品吧！");
            return;
        }

        System.out.printf("%-6s | %-10s | %-8s | %-4s | %-8s%n",
                "商品ID", "商品名称", "单价(元)", "数量", "小计(元)");
        System.out.println("------------------------------------------------");

        double total = 0.0;

        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            int quantity = entry.getValue();
            Product product = productService.getProductById(productId);

            if (product == null) {
                System.out.printf("%-6s | %-10s | %-8s | %-4d | %-8s%n",
                        productId, "【已下架】", "---", quantity, "---");
                continue;
            }

            double price = product.getPrice();
            double subtotal = price * quantity;
            total += subtotal;

            System.out.printf("%-6s | %-10s | %-8.2f | %-4d | %-8.2f%n",
                    productId, product.getName(), price, quantity, subtotal);
        }

        System.out.println("------------------------------------------------");
        System.out.printf("总金额：%.2f元%n", total);
    }

    public static void main(String[] args) {
        new ConsoleShop().start();
    }
}